package cn.edu.suda.vote.vote;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class StartActivity extends AppCompatActivity {

    private final static int MSG_SUCCESS = 1;
    private final static int MSG_FAILURE = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                startActivity(new Intent(StartActivity.this, MainActivity.class));
                finish();
            } else {
                Toast.makeText(StartActivity.this, "初始化失败！请点击 开始投票 按钮！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        Button button = (Button) findViewById(R.id.start_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setVoter();
            }
        });
    }

    private void setVoter() {
        String url = "http://192.168.2.100:8080/androidServer/setVoteInfo";
        RequestBody requestBody = new FormBody.Builder().add("model", Build.MODEL).build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                handler.obtainMessage(MSG_FAILURE).sendToTarget();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                handler.obtainMessage(MSG_SUCCESS).sendToTarget();

            }
        });
    }
}
